<?php

namespace app\model;

use think\model\concern\SoftDelete;

class ProductCategoryModel extends BaseModel
{
    protected $name = 'product_category';


    use SoftDelete;

    /**
     * 软件删除
     *
     * @var string
     * @Author YangHB
     * @DateTime 2022-07-12 21:05:32
     *
     */
    protected $deleteTime = "deleted_at";


    /**
     * Notes: 树形列表
     * User: chenLei
     * Date: 9/25/25
     * @param $params
     * @return array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function treeList($params)
    {
        $list = $this->where('pid', 0)->select();

        foreach ($list as $key => $value) {
            $list[$key]['child'] = $this->where('pid', $value['id'])->select();
        }

        return $list;
    }

    /**
     * Notes: 获取顶级分类
     * User: chenLei
     * Date: 9/25/25
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function topList()
    {
        return $this->where('pid', 0)->select();
    }

    /**
     * Notes: 添加产品分类
     * User: chenLei
     * Date: 9/24/25
     * @param $params
     * @return true
     */
    public function add($params)
    {
        $this->save([
            'name' => $params['name'],
            'pid' => $params['pid'] ?? 0
        ]);

        return true;
    }


    /**
     * Notes: 编辑产品分类
     * User: chenLei
     * Date: 9/25/25
     * @param $params
     * @return bool
     */
    public function edit($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '分类不存在';
            return false;
        }

        if ($params['pid'] == $info['id']) {
            $this->error = '上级分类不能是自己';
            return false;
        }

        $info->save([
            'name' => $params['name'],
            'pid' => $params['pid'] ?? 0
        ]);

        return true;
    }


    /**
     * Notes: 删除产品分类
     * User: chenLei
     * Date: 9/25/25
     * @param $params
     * @return bool
     */
    public function del($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '分类不存在';
            return false;
        }

        if ($this->where('pid', $info['id'])->count()) {
            $this->error = '请先删除子分类';
            return false;
        }

        $info->delete();
        return true;
    }
}